package com.tigerlee.stopmusic;

import java.lang.ref.WeakReference;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.vimana.widgets.progressbar.SaundProgressBar;

public class StopProgressActivity extends AbstractActivity implements OnClickListener{
	
	private SaundProgressBar mRegularProgressBar;
	
	private final int ID_STOP_SERVICE = 1;
	private static final int ID_CHECK_TURN_OFF_MUSIC = 2;
	private static final int ID_CHECK_TURN_OFF_WIFI = 3;
	private static final int ID_CHECK_TURN_OFF_BT = 4;
	
	public static final int UPDATE_PROGRESS = 100;
	private static final String TAG = "StopProgressActivity";
	
	private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if(action != null && action.equals(UpdateNotificationReceiver.INTENT_ACTION_FINISH_TASK)){
				finishThisActivity();
			}else if(action != null && action.equals(Intent.ACTION_TIME_TICK)){
				setTimePanelView(mIsSetTime);
				setProgressTimePanelView(false);
			}
		}
	};
	static class MyHandler extends Handler{
		WeakReference<StopProgressActivity> mWeakReference;
		public MyHandler(StopProgressActivity activity) {
			mWeakReference = new WeakReference<StopProgressActivity>(activity);
		}
		@Override
		public void handleMessage(Message msg) {
			if(msg.what == UPDATE_PROGRESS){
				// Call updateProgress method like infinite callback
				StopProgressActivity activity = mWeakReference.get();
				activity.updateProgress();
			}
		}
	};
	
	private MyHandler mHandler = new MyHandler(this);
	private long mStartTime;
	private long mStopTime;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		
		if(mIsSetTime){
			setContentView(R.layout.activity_stop_alarm_time);
		}else{
			setContentView(R.layout.activity_stop_alarm_min);
		}
		// get stoptime and set as alarm time
		mAlarm.setAlarmTimeByTimeMills(mPreference.getStopTime());

		// Get start and stop time from preference
		mStartTime = mPreference.getStartTime();
		mStopTime = mPreference.getStopTime();

		Button button = (Button) findViewById(R.id.button_cancel);
		button.setVisibility(View.VISIBLE);
		button.setId(ID_STOP_SERVICE);
		button.setOnClickListener(this);
		
		button = (Button) findViewById(R.id.checkbox_music);		
		button.setId(ID_CHECK_TURN_OFF_MUSIC);
		button.setOnClickListener(this);
		if(mPreference.isTurnOffMusic()){
			button.setBackgroundResource(R.drawable.checkbox_checked);
		}
		
		button = (Button) findViewById(R.id.checkbox_wifi);
		button.setId(ID_CHECK_TURN_OFF_WIFI);
		button.setOnClickListener(this);
		if(mPreference.isTurnOffWifi()){
			button.setBackgroundResource(R.drawable.checkbox_checked);
		}
		
		button = (Button) findViewById(R.id.checkbox_bluetooth);
		button.setId(ID_CHECK_TURN_OFF_BT);
		button.setOnClickListener(this);
		if(mPreference.isTurnOffBluetooth()){
			button.setBackgroundResource(R.drawable.checkbox_checked);
		}

		// Call to set TextView from AbstractActivity 
		setTimePanelView(mIsSetTime);
		
		// get ProgressBar and set indicator
		mRegularProgressBar = (SaundProgressBar) findViewById(R.id.regularprogressbar);
		Drawable indicator = getResources().getDrawable(R.drawable.progress_indicator);
		Rect bounds = new Rect(0, 0, indicator.getIntrinsicWidth() + 15,
				indicator.getIntrinsicHeight()+15);
		indicator.setBounds(bounds);
		mRegularProgressBar.setProgressIndicator(indicator);
		
		// Toggle boolean and set time
		setProgressTimePanelView(false);
		
		// Register broadcastReceiver
		IntentFilter intentFilter = new IntentFilter(UpdateNotificationReceiver.INTENT_ACTION_FINISH_TASK);
		intentFilter.addAction(Intent.ACTION_TIME_TICK);
		registerReceiver(mBroadcastReceiver, intentFilter);
		// Start updating immediately as infinity loop
		updateProgress();
		// Call from AbstractActivity.. Admob will be set here
		setAdView();
		// Check if state is changed and it has been passed..
		checkState();		
		
	}
	private void checkState() {
		// Check if state is changed and it has been passed..
		if (mIsRunning == false|| mPreference.getStopTime() < System.currentTimeMillis()) {
			mPreference.initPreference();
			startActivity(new Intent(this, StopMusicActivity.class));
			finish();
		}
	}
	@Override
	protected void onPause() {
		// Cancel updating progressBar
		mHandler.removeMessages(UPDATE_PROGRESS);
		unregisterReceiver(mBroadcastReceiver);
		super.onPause();
		
	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		switch (id) {
		case ID_STOP_SERVICE:
			finishThisActivity();
			break;
		case ID_CHECK_TURN_OFF_MUSIC:
			if(mPreference.isTurnOffMusic() == true){
				mPreference.setTurnOffMusic(false);
				v.setBackgroundResource(R.drawable.checkbox_uncheck);
			}else{
				mPreference.setTurnOffMusic(true);
				v.setBackgroundResource(R.drawable.checkbox_checked);
			}
			setProgressTimePanelView(true);
			break;
		case ID_CHECK_TURN_OFF_WIFI:
			if(mPreference.isTurnOffWifi() == true){
				mPreference.setTurnOffWifi(false);
				v.setBackgroundResource(R.drawable.checkbox_uncheck);
			}else{
				mPreference.setTurnOffWifi(true);
				v.setBackgroundResource(R.drawable.checkbox_checked);
			}
			setProgressTimePanelView(true);
			break;
		case ID_CHECK_TURN_OFF_BT:
			if(mPreference.isTurnOffBluetooth() == true){
				mPreference.setTurnOffBluetooth(false);
				v.setBackgroundResource(R.drawable.checkbox_uncheck);
			}else{
				mPreference.setTurnOffBluetooth(true);
				v.setBackgroundResource(R.drawable.checkbox_checked);
			}
			setProgressTimePanelView(true);
			break;
		default:
			break;
		}
	}
	private void finishThisActivity() {
		// Cancel all alarmManager services..
		WidgetControlReceiver.cancelAlarmService(getApplicationContext());
		
		// Broadcast cancel action to interrupt thread progress and stop a notification
		sendBroadcast(new Intent(UpdateNotificationReceiver.INTENT_ACTION_FINISH_TASK));
		
		// Show stop music activity to reset alarm time... 
		Intent intent = new Intent(getApplicationContext(), StopMusicActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(intent);
		
		finish();
	}

	protected void updateProgress() {
		Log.d(TAG, "updateProgress");
		long ONE_SECOND = 1 * 1000;
		int passedSeconds = (int)((System.currentTimeMillis() - mStartTime) / ONE_SECOND );
		int remainSeconds = (int) ((mStopTime - mStartTime) / ONE_SECOND);
		mRegularProgressBar.setMax(remainSeconds);
		// Set current time for progress Bar
		mRegularProgressBar.setProgress(passedSeconds);
		if(mRegularProgressBar.getProgress() >= mRegularProgressBar.getMax()){ // terminate this infinite callback
			Log.d(TAG, "getProgress >= getMax");
			return;
		}
		//send at delay time(1 sec) to update progressBar
		mHandler.sendEmptyMessageDelayed(UPDATE_PROGRESS, ONE_SECOND);
	}
	
	public void setProgressTimePanelView(boolean isShowToast) {
		String state = changeTextStringByState(getApplicationContext());
		if(state == "" && isShowToast){
			state = getString(R.string.text_nothing);
			Toast.makeText(getApplicationContext(), getString(R.string.toast_nothing), Toast.LENGTH_LONG).show();
		}
		state = getString(R.string.text_stop) + " " + state;
		String postfix = mIsSetTime ? " " + getString(R.string.text_after) : " " + getString(R.string.text_at);
		
		TextView textView = (TextView) findViewById(R.id.text_time_info);
		textView.setText(state + postfix);
		
		textView = (TextView) findViewById(R.id.text_time_remain_below);
		postfix = mIsSetTime ? " " + getString(R.string.text_at) : " " + getString(R.string.text_after);
		textView.setText(state + postfix);
				
		// set time by opposite way with panel
		if (!mIsSetTime) {// (TimeView) set stopping music by duration
			// Calculate and then set current time
			String[] results = mAlarm.getRemainTimeToString(mAlarm.getAlarmTimeMillis());
			String hours = "";
			// NOT SET hours if zero 
			if(!results[0].equals("00")) hours = getString(R.string.hours, results[0]);
			String mins = getString(R.string.minutes, results[1]);
			String duration  = "\n" + hours + " " + mins;
			textView.append(duration);
		} else {// (Duration) set stopping music by time
			textView = (TextView) findViewById(R.id.text_time_remain_below);
			// Calculate and then set current time
			String time = "\n" + String.format("%02d", mAlarm.getAlarmHour()) + ":"
					+ String.format("%02d", mAlarm.getAlarmMinute())
					+ mAlarm.getAMPM();
			textView.append(time);
		}
	}
	
	public static String changeTextStringByState(Context context){
		String state = "";
		MyPreference preference = new MyPreference(context);
		if (preference.isTurnOffMusic()) {
			state += context.getString(R.string.text_music);
		}
		if (preference.isTurnOffWifi()) {
			if (state != "") {
				state += "/";
			}
			state += context.getString(R.string.text_wifi);
		}
		if (preference.isTurnOffBluetooth()) {
			if (state != "") {
				state += "/";
			}
			state += context.getString(R.string.text_bluetooth);
		}
		return state;
	}
}
